import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import Layout from '@/layouts/Layout.vue'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false,
    },
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: {
      requiresAuth: true,
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
          title: '看板',
          icon: 'DashboardOutlined',
          keepAlive: true,
          requiresAuth: true,
        },
      },
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/User.vue'),
        meta: {
          title: '用户管理',
          icon: 'UserOutlined',
          keepAlive: true,
          requiresAuth: true,
        },
      },
      {
        path: '/settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: {
          title: '系统设置',
          icon: 'SettingOutlined',
          keepAlive: true,
          requiresAuth: true,
        },
      },
      {
        path: '/article',
        name: 'Article',
        component: () => import('@/views/article/index.vue'),
        meta: {
          title: '文章管理',
          icon: 'FileTextOutlined',
          keepAlive: true,
          requiresAuth: true,
        },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫 - 强制登录
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token

  // 如果访问的是登录页面
  if (to.path === '/login') {
    // 如果已登录，跳转到首页
    if (token) {
      next('/dashboard')
    } else {
      next()
    }
    return
  }

  // 如果页面需要登录
  if (to.meta.requiresAuth) {
    if (!token) {
      message.warning('请先登录')
      next('/login')
      return
    }
  }

  next()
})

export default router
